package com.chat.wesocket.handler;

import com.alibaba.fastjson2.JSON;
import com.chat.security.entity.JWTLoginUser;
import com.chat.security.service.JwtTokenService;
import com.chat.wesocket.constant.WsConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeFailureException;
import org.springframework.web.socket.server.HandshakeHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Component
public class WsHandShakeHandler implements HandshakeInterceptor {

    @Autowired
    JwtTokenService jwtTokenService;
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        System.out.println("handshake");
        final HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
        final String token = servletRequest.getParameter("token");
        final Map<String, Object> claims = jwtTokenService.getClaims(token);
        final String o = (String) claims.get(JwtTokenService.LOGIN_USER_KEY);
        final JWTLoginUser jwtLoginUser = JSON.parseObject(o, JWTLoginUser.class);
        System.out.println(jwtLoginUser);
        attributes.put(WsConstant.WS_LOGIN_USER_KEY,jwtLoginUser);
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}
